package com.shujia.spark.opt

import org.apache.spark.rdd.RDD
import org.apache.spark.{SparkConf, SparkContext}

object Demo0Agg {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf()
    conf.setMaster("local")
    conf.setAppName("agg")

    val sc = new SparkContext(conf)


    val linesDS: RDD[String] = sc.textFile("data/words.txt")

    val kvDS: RDD[(String, Int)] = linesDS.flatMap(_.split(",")).map((_, 1))

    /**
      * aggregateByKey: 对同一个key进行聚合计算，
      * 需要指定初始值，map端的聚合函数，reduce端的聚合函数
      *
      */

    val countRDD: RDD[(String, Int)] = kvDS.aggregateByKey(0)(
      (zero: Int, v: Int) => zero + v,//在map端进行预聚合的函数
      (u1: Int, u2: Int) => u1 + u2//在reduce端将结果合并的函数
    )

    countRDD.foreach(println)


  }

}
